package se.webbzon.boltzmann;

import se.webbzon.boltzmann.loader.Loader;
import se.webbzon.boltzmann.loader.LoaderException;
import se.webbzon.boltzmann.loader.LoaderUtility;
import se.webbzon.boltzmann.loader.LoaderUtilityListener;
import se.webbzon.boltzmann.loader.LoaderUtilityPointer;
import se.webbzon.boltzmann.Main;

public class ResourceLoader {
	
	// The loader utility for this resource loader
	private final LoaderUtility lu;
	
	/*============================================================
	Constructors
	============================================================*/
	
	/** Creates a new resource loader. **/
	public ResourceLoader() {
		lu = new LoaderUtility();
	}
	
	/*============================================================
	Public Methods
	============================================================*/
	
	/** Loads all the available resources by parsing the given
	 * resource root XML-file. **/
	public synchronized int load(String root, Loader ... loaders) throws LoaderException {
		for (Loader loader : loaders)
			lu.addLoader(loader);
		
		LoaderUtilityListenerImpl listener = new LoaderUtilityListenerImpl();
		lu.addListener(listener);
		lu.loadFromXML(Main.class.getClassLoader().getResource(root));
		
		for (Loader loader : loaders)
			lu.removeLoader(loader);
		
		return listener.resources();
	}
	
	/*============================================================
	Private Classes
	============================================================*/
	
	private final class LoaderUtilityListenerImpl implements LoaderUtilityListener {

		// The number of loaded resources
		private int resources = 0;
		
		@Override public void onLoadBegin(LoaderUtility utility, LoaderUtilityPointer pointer) {};

		@Override public void onLoadEnd(LoaderUtility utility, LoaderUtilityPointer pointer) {
			resources++;
		}
		
		/** Returns the number of loaded resources. **/
		public int resources() {
			return resources;
		}
		
	}

}
